﻿using FluentValidation;
using TaskMasterByQuartz.Domain.Enums;
using TaskMasterByQuartz.Domain.InterfaceRepository;

namespace TaskMasterByQuartz.WebAPI.Controllers.Req
{
    /// <summary>
    /// 创建任务请求信息
    /// </summary>
    public record JobInfoReq
    {
        /// <summary>
        /// 任务分组
        /// </summary>
        public string JobGroup { get; init; }
        /// <summary>
        /// 任务名称
        /// </summary>
        public string JobName { get; set; }
        /// <summary>
        /// 任务类型
        /// </summary>
        public JobTypeEnum JobType { get; set; } = JobTypeEnum.Url;
        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTimeOffset BeginTime { get; set; } = DateTime.Now;
        /// <summary>
        /// 结束时间
        /// </summary>
        public DateTimeOffset? EndTime { get; set; }
        /// <summary>
        /// Cron表达式
        /// </summary>
        public string? Cron { get; set; }
        /// <summary>
        /// 执行次数（默认无限循环）
        /// </summary>
        public int? RunTimes { get; set; }
        /// <summary>
        /// 执行间隔时间，单位秒（如果有Cron，则IntervalSecond失效）
        /// </summary>
        public int IntervalSecond { get; set; }
        /// <summary>
        /// 触发器类型
        /// </summary>
        public TriggerTypeEnum TriggerType { get; set; }
        /// <summary>
        /// 描述
        /// </summary>
        public string Description { get; set; }

        #region Url
        /// <summary>
        /// 请求url
        /// </summary>
        public string RequestUrl { get; set; }
        /// <summary>
        /// 请求参数（Post，Put请求用）
        /// </summary>
        public string? RequestParameters { get; set; }
        /// <summary>
        /// Headers(可以包含如：Authorization授权认证)
        /// 格式：{"Authorization":"userpassword.."}
        /// </summary>
        public string? Headers { get; set; }
        /// <summary>
        /// 请求类型
        /// </summary>
        public RequestTypeEnum RequestType { get; set; } = RequestTypeEnum.Post;
        #endregion

        public class JobInfoReqValidator : AbstractValidator<JobInfoReq>
        {
            private readonly ISchedulerCenter _schedulerCenter;

            public JobInfoReqValidator(ISchedulerCenter schedulerCenter)
            {
                _schedulerCenter = schedulerCenter;

                RuleFor(x => x.RequestUrl)
                    .NotEmpty().WithMessage("RequestUrl不能为空。")
                    .Must(BeValidUrl).WithMessage("RequestUrl必须是有效的URL。");

                RuleFor(x => x).Must(NotExistJob).WithMessage("任务已存在。");
            }

            private bool BeValidUrl(string url)
            {
                Uri uriResult;
                return Uri.TryCreate(url, UriKind.Absolute, out uriResult)
                    && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
            }

            private bool NotExistJob(JobInfoReq request)
            {
                bool isJobExists = _schedulerCenter.CheckScheduleJobAsync(request.JobGroup, request.JobName).GetAwaiter().GetResult();
                return !isJobExists;
            }
        }
    }
}
